package com.walkline.screen;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import com.walkline.smzdm.SMZDMException;
import com.walkline.smzdm.SMZDMSDK;
import com.walkline.smzdm.inf.ExperienceDetails;
import com.walkline.smzdm.inf.ExperienceList;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;

public class RefreshContentsScreen extends PopupScreen
{
	Thread thread=null;
	SMZDMSDK _smzdm;
	String _param;
	ExperienceList _experienceList;
	ExperienceDetails _experienceDetails;

	public RefreshContentsScreen(SMZDMSDK smzdm, String param, int action)
	{
		super(new VerticalFieldManager());

		_smzdm = smzdm;
		_param = param;

		add(new LabelField("Please wait....", Field.FIELD_HCENTER));

		switch (action)
		{
			case RefreshActions.EXPERIENCELIST:
				thread = new Thread(new ExperienceListRunnable());
				break;
			case RefreshActions.EXPERIENCEDETAILS:
				thread = new Thread(new ExperienceDetailsRunnable());
		}

		thread.start();
	}

	class ExperienceListRunnable implements Runnable
	{
		public void run()
		{
			try {
				_experienceList = _smzdm.getExperienceList(_param);

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (SMZDMException e) {Function.errorDialog(e.toString());}
		}
	}

	class ExperienceDetailsRunnable implements Runnable
	{
		public void run()
		{
			try {
				_experienceDetails = _smzdm.getExperienceDetails(_param);

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (SMZDMException e) {Function.errorDialog(e.toString());}
		}
	}

	public ExperienceList getExperienceList() {return _experienceList;}

	public ExperienceDetails getExperienceDetails() {return _experienceDetails;}

	public boolean onClose()
	{
		if (thread != null)
		{
			try {
				thread.interrupt();
				thread = null;
			} catch (Exception e) {}
		}

		try {
			UiApplication.getUiApplication().popScreen(this);	
		} catch (Exception e) {}

		return true;
	}

	protected boolean keyChar(char key, int status, int time)
	{
		if (key == Characters.ESCAPE)
		{
			onClose();

			return true;
		}

		return super.keyChar(key, status, time);
	}
} 